<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com> <http://www.jxlnxx.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;

/**
 * API商品控制器
 * 主要获取商品数据
 * 
 * @author Ringo Chan <334258471@qq.com>
 */
class ProductController extends ApiController{
    
    /**
     * 获取出售中商品列表
     * 
     * @param string type 商品类型 
     * @param integer page 页码
     * @param integer pagesize 每页数据总数
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getProducts(){
        params_exist('type');
        $type = I('post.type', 0); // 商品类型
        $page = I('post.page', 1); // 页码
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        $category_id = I('post.category_id'); // 商品分类编号
        $in_special_panic = I('post.in_special_panic', 0); // TRUE：查询加入了抢购会的商品
        $in_special_gift = I('post.in_special_gift', 0); // TRUE:查询加入了选礼物的商品
        $panic_id = I('post.panic_id'); // 抢购会时间段编号
        $panic_sortdiscount = I('post.panic_sortdiscount', 0); // TRUE：根据抢购会折扣排序
        $panic_endtime = I('post.panic_endtime'); // 已开始抢购但尚未结束的商品
        $gift_id = I('post.gift_id'); // 选礼物分类编号
        $sort_view = I('post.sortview', 0);
        $map['name']=array('eq','putong');
        $map['type']=array('eq','putong');


        
        $options = array();
        $model = M('product');
        $M_product_special_panic = M('product_special_panic');
        $map=array();
        if ($type == 'putong' && $in_special_panic && (!empty($panic_id) || !empty($panic_sortdiscount) || !empty($panic_endtime))) {
            $prefix = C('DB_PREFIX');
            $l_table = $prefix.('product');
            $m_table = $prefix.('product_special_panic');
            $r_table = $prefix.('special_panic');

            $model = $model->table($l_table.' l')->join($m_table.' m ON m.product_id=l.id')->join($r_table.' r ON r.id = m.special_panic_id ');

            $options['field'] = array('l.id', 'l.title', 'l.view', 'l.price', 'l.quantity');
            $options['order'] = 'l.id DESC';
            $sort_view && $options['order'] = 'l.view DESC, l.id DESC';
            $panic_sortdiscount && $options['order'] = 'm.discount DESC, l.id DESC';

            $map['l.status'] = 1;
            $map['l.is_show'] = 1;
            $map['l.type'] = $type;
            $map['l.in_special_panic'] = $in_special_panic;
            if (!empty($category_id)) {
                $categories = M('product_category')->where(array('path'=>array('like','%,'.$category_id.",%")))->select();
                $ids = array();
                foreach ($categories as $category) {
                    $ids[] = $category['id'];
                }
                $map['l.category_id'] = array('in', $ids);
            }
            $panic_id && $map['m.special_panic_id'] = $panic_id;
            $panic_endtime && $map['r.end_time'] = array('elt', $panic_endtime);
            $options['where'] = $map;
        } elseif ($type == 'putong' && $in_special_gift && !empty($gift_id)) {
            $prefix = C('DB_PREFIX');
            $l_table = $prefix.('product');
            $m_table = $prefix.('product_special_gift');
            $r_table = $prefix.('special_gift');

            $model = $model->table($l_table.' l')->join($m_table.' m ON m.product_id=l.id')->join($r_table.' r ON r.id = m.special_gift_id');
            
            $options['field'] = array('l.id', 'l.title', 'l.price', 'l.quantity');
            $options['group'] = 'l.id';
            $options['order'] = 'l.id DESC';
            $map['l.is_show'] = 1;
            $map['l.status'] = 1;
            $map['l.type'] = $type;
            $map['l.in_special_gift'] = $in_special_gift;
            if (!empty($category_id)) {
                $categories = M('product_category')->where(array('path'=>array('like','%,'.$category_id.",%")))->select();
                $ids = array();
                foreach ($categories as $category) {
                    $ids[] = $category['id'];
                }
                $map['l.category_id'] = array('in', $ids);
            }
            $map['m.special_gift_id'] = $gift_id;
            $options['where'] = $map;
        }elseif ($type=='score'){
            $prefix = C('DB_PREFIX');
            $l_table = $prefix.('product');
            $r_table = $prefix.('special_gift');
            $model = $model->table($l_table.' l');
            $options['field'] = array('l.id','l.price', 'l.title', 'l.use_score', 'l.quantity');
            $options['group'] = 'l.id';
            $options['order'] = 'l.id DESC';
            $map['l.is_show'] = 1;
            $map['l.status'] = 1;
            $map['l.type'] = $type;
            $options['where'] = $map;
        } else {
            $map['is_show'] = 1;
            $map['status'] = 1;
            $map['type'] = $type;
            if (!empty($category_id)) {
                $categories = M('product_category')->where(array('path'=>array('like','%,'.$category_id.",%")))->select();
                $ids = array();
                foreach ($categories as $category) {
                    $ids[] = $category['id'];
                }
                $map['category_id'] = array('in', $ids);
            }
            if($type =='paipin'){
                $options['field']=array_merge($options['field'],array('start_time','end_time'));
            }
            $options['field'] = array('id', 'title', 'view', 'price', 'quantity');
            $options['order'] = 'id DESC';
            $sort_view && $options['order'] = 'view DESC, id DESC';
            $options['where'] = $map;
        }
        $OPT = new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
   
        $options = array_merge( (array)$OPT->getValue($model), $options );
        $total = $model->where($options['where'])->count();
      
        if ($page > 0 && $pagesize > 0) {
            $start = ($page - 1) * $pagesize;
            $options['limit'] = $start.','.$pagesize;
        }
        
        $model->setProperty('options',$options);
   
        $list = $model->select();

        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');
        foreach ($list as $key => $item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();

            $list[$key]['image'] = get_url($image_info['cover_id'], 'path');
        }

        foreach ($list as $key => $item) {
            $discount = $M_product_special_panic->where(array('product_id'=>$item['id']))->getField('discount');
            $tmp_price = number_format($item['price']*(0.1*$discount),2);
            $list[$key]['now_price']=number_format($item['price']*(0.1*$discount),2);
        }

        $list === false && response(-9);
        $result = array(
            'total' => $total,
            'result' => $list
        );
        response(1, $result);
    }
    /**
     * 拍品列表
     * @param string category_id 商品分类
     * @param integer page 页码
     * @param integer pagesize
     * @param int is_delicacy 是否是精选
     * @param int starttime 即将开始
     * @param int endtime 即将结束
     * @param int price_start
     */
    public function getpaipinList(){

        $start_time=I('post.starttime');
        $end_time=I('post.endtime');
        $category_id=I('post.category_id');
        $page=I('post.page',1);
        $pagesize=I('post.pagesize',10);
        
        $price_start=I('post.price_start');
        (int)$page<1 && $page=1;
        $offset=($page-1)*$pagesize;
        
        $M_product=M('product');
        $M_product_image=M('product_image');
        $M_activity=M('product_special_activity');
        $map=array();
        $map['type']="paipin";
        $map['status']=1;
        $map['is_show'] = 1;
        
        I('post.is_delicacy')==1 &&   $map['is_delicacy']=1;
        $price_start !=='' && $map['price_start']=$price_start;
        if($start_time){
            $map['start_time']=array('BETWEEN',$start_time+3600);
        }
        
        if($end_time){
            $map['end_time']=array('BETWEEN',$end_time+3600);
        }
        !(empty($category_id) || !is_numeric($category_id)) && $map['category_id'] = $category_id;
        $list=$M_product->where($map)->limit($offset,$pagesize)
        ->field('id,title,category_id,paipin_activity_id,start_time,end_time,is_delicacy,auction_count,price_start,maxprice')
        ->select();
        $total=$M_product->where($map)->count();
        foreach ($list as &$item){
            $image_info = $M_product_image
            ->where(array('product_id'=>$item['id']))
            ->order('id ASC')->find();
            $activity_info=$M_activity->find($item['paipin_activity_id']);
            $item['activity_title']=$activity_info['title'];
            $item['activity_short_desc']=$activity_info['short_desc'];
            $item['image'] = get_url($image_info['cover_id'], 'path');
        }
        $result=array();
        $result['total']=$total;
        $result['result']=$list;
        $list ? response(1,$result) : response(-2);
    }
    
    
    /**
     * 获取出售中商品列表
     *
     * @param string category_id 商品分类
     * @param integer page 页码
     * @param integer pagesize 每页数据总数
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getProductList(){
      
        $page = I('post.page', 1); // 页码
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        $category_id = I('post.category_id'); // 商品分类编号
        $start=0;
        
        $product = M('product');
        $map=array();
        $map['status'] = 1;
        $map['is_show'] = 1;
       !(empty($category_id) || !is_numeric($category_id)) && $map['category_id'] = $category_id;

       if ($page > 0 && $pagesize > 0) {
           $start = ($page - 1) * $pagesize;           
       }
       
        $total=$product->where($map)->count();
        $list = $product->limit($start,$pagesize)->where($map)->field('id,title,price,quantity')->order('id ASC')->select();
    
        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');
    
        foreach ($list as $key => $item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();
    
            $list[$key]['image'] = get_url($image_info['cover_id'], 'path');
        }
    
        $list === false && response(-9);
    
        $result = array(
            'total' => $total,
            'result' => $list
        );
    
        response(1, $result);
    }
    
    /**
     * 获取我的商品列表
     * 
     * @param string type 商品类型
     * @param integer page 页码
     * @param integer pagesize 每页数据总数
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getMyProducts(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('type'));
    
        $type = I('post.type', 0); // 商品类型
        $page = I('post.page', 1); // 页码
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        $status = I('post.status'); // 商品状态

        if($status !== ''){
            !preg_match('/^0|1$/', $status) && response(-2,'状态值错误');
            $map['status']=$status;
        }
        !get_table_field($type, 'name', 'id', 'product_type') && response(-2, '', '无效商品类型');
        
        $options = array();
        $model = M('product');
        
        
        $map['uid'] = API_UID;
        $map['type'] = $type;
        $map['is_show'] = 1;
        
        $options['where'] = $map;
        $options['field'] = array('id', 'title','sales', 'price', 'quantity','type','status');
        $options['order'] = 'id DESC';

        $OPT = new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
        
        $options = array_merge( (array)$OPT->getValue($model), $options );
        $total = $model->where($options['where'])->count();
        
        if ($page > 0 && $pagesize > 0) {
            $start = ($page - 1) * $pagesize;
            $options['limit'] = $start.','.$pagesize;
        }
        
        $model->setProperty('options',$options);

        $list = $model->select();
    
        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');
    
        foreach ($list as $key => $item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();
    
            $list[$key]['image'] = get_cover($image_info['cover_id'], 'path');
        }
    
        $list === false && response(-9);

        $result = array(
            'total' => $total,
            'result' => $list
        );

        response(1, $result);
    }
    
    /**
     * 商品 上架
     * @param int id
     * 
     */
    public function myproductPutaway(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        $id = I('post.id', 0);
        
        $M_product = M('product');
        
        $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
        
        $info = $M_product->where($map)->find();

//        //==判断商户积分是否足够商品的积分
//        $member = M('member')->where('uid='.API_UID)->find();
//        if($member['score']<$info['score'])
//        {
//            response(-3,'您的积分不足商品赠送积分不能上架！');
//        }

        empty($info) && response(-2,'商品不存在');
        
        $M_product->where($map) ->setfield('status',1) ? response(1) : response(-9);
    }
    
    /**
     * 商品 下架
     * @param int id
     *
     */
    public function myproductHalt (){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
         $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
    
        $info = $M_product->where($map)->find();
    
        empty($info) && response(-2,'商品不存在');
    
        $M_product->where($map) ->setfield('status',0)  ? response(1) : response(-9);
    }
    
    /**
     * 商品 下架
     * @param int id
     *
     */
    public function myproductDel (){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
        $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
    
        $info = $M_product->where($map)->find();
    
        empty($info) && response(-2,'商品不存在');
    
        $M_product->where($map) ->setfield('is_show',0)  ? response(1) : response(-9);;
    }
    
    /**
     * 我的商品详情
     *
     * @param integer id 商品编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getMyProduct(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        params_exist(array('id'));
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
        $info = $M_product->where(array('id'=>$id, 'uid'=>API_UID,'is_show'=>1))->find();
    
        !$info && response(-2, '', '没有找到匹配商品');
        
        $result = array();
    
        switch ($info['type']) {
            case 'putong':
                $M_product_special_panic = M('product_special_panic');
                $info['in_special_panic'] == 1 && $result['special_panic'] = $M_product_special_panic->where(array('product_id'=>$id))->select();
                $fields = array('id', 'uid','score', 'shop_id', 'category_id', 'title', 'description', 'price', 'quantity', 'movie',
                    'security_7days', 'security_delivery', 'in_special_panic', 'in_special_gift',
                    'status','province_id','city_id','area_id','address','sales');
                break;
            case 'paipin':
                $fields = array('id', 'uid', 'shop_id', 'category_id', 'title', 'description', 'price',
                'maxprice', 'quantity', 'movie', 'start_time', 'end_time', 'security_7days',
                'security_delivery',
                'status','province_id','city_id','area_id','address','sales');
                break;
            case 'xianzhi':
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity',
                'movie', 'security_7days', 'security_delivery','status','province_id','city_id',
                'area_id','address','sales');
                break;
            default:
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity',
                'movie', 'security_7days', 'security_delivery','status','province_id','city_id','area_id',
                'address','sales','score');
                break;
        }
    
        foreach ($fields as $field){
            $result[$field] = $info[$field];
        }
        
         $result['status_text'] =getStatus('product')[$result['status']];
         $result['address_full']=
         get_table_field($info['province_id'],'province_id','province','hat_province')
         .get_table_field($info['city_id'],'city_id','city','hat_city')
         .get_table_field($info['area_id'],'area_id','area','hat_area')
         .$info['address'] ;
        $result['category_title']=get_table_field($info['category_id'],'id','title','product_category');
        $M_product_image = M('product_image');
        $images = $M_product_image->where(array('product_id'=>$id))->select();
        foreach ($images as $image) {
            $result['images'][] = array(
                'id' => $image['id'],
                'cover_id'=>$image['cover_id'],
                'path' => get_cover($image['cover_id'], 'path')
            );
        }    
        if($info['movie']){
            $result['movie'] = array(
                'thumb_image_path'=>get_url(get_movie($result['movie'],'thumb_cover_id')),
                'id' => $info['movie'],
                'path' => mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Uploads/Movie/' . get_movie($result['movie'], 'savepath') . get_movie($result['movie'], 'savename'),
                'mime' => get_movie($result['movie'], 'mime')
            );
        }else{
            $result['movie']=null;
        }
        
        //组合属性
        $M_option=M('product_option');
        $o_names=$M_option->where(array('product_id'=>$id,'pid'=>0))->select()|0;
        foreach ($o_names as &$item){
            $item['_child']=$M_option->where(array('pid'=>$item['id']))->select();
        }
    
        //组合价格
        $M_product_option_price=M('product_option_price');
        $result['option_price']=$M_product_option_price
        ->where(array('product_id'=>$id))->field('product_option_id,price')->select()|$result['price'];
    
        $result['option']=$o_names;
        response(1, $result);
    }
    
    /**
     * 获取出售中商品详情
     * 
     * @param integer id 商品编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getProduct(){
        params_exist(array('id'));
        
        $id = I('post.id', 0);
        
        $M_product = M('product');
        
        $info = $M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
        
        !$info && response(-2, '', '没有找到匹配商品');
        
        $M_product->where(array('id'=>$id, 'status'=>1))->setInc('view');

        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        if(API_UID){
            $M_browse=M('collect_browse');
            $colmap=array('uid'=>API_UID,'product_id'=>$id);
            $bro_id=$M_browse->where($colmap)->find();
            if(empty($bro_id)){
                $M_browse->add(array('uid'=>API_UID,'create_time'=>NOW_TIME,'product_id'=>$id,'ip'=>get_client_ip(1)));
            }else{
                $M_browse->where($colmap)->save(array('create_time'=>NOW_TIME,'ip'=>get_client_ip(1)));
            }
            
            $M_cr_s=M('collect_browse_shop');
            $shoplmap=array('uid'=>API_UID,'shop_id'=>$info['shop_id']);
            $brow_shop=$M_cr_s->where($shoplmap)->find();
            if(empty($brow_shop)){
                $M_cr_s->add(array('uid'=>API_UID,'create_time'=>NOW_TIME,'shop_id'=>$info['shop_id'],'ip'=>get_client_ip(1)));
            }else{
                $M_cr_s->where($shoplmap)->save(array('create_time'=>NOW_TIME,'ip'=>get_client_ip(1) ));
            } 
        }
        
        $result = array(); 
        
        switch ($info['type']) {
            case 'putong':
                $M_product_special_panic = M('product_special_panic');
                $info2=$M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
                $info2['in_special_panic'] == 1 && $result['special_panic'] = $M_product_special_panic->where(array('product_id'=>$id))->select();
                $fields = array('id', 'uid', 'shop_id', 'category_id', 'title', 'description', 'price', 'quantity', 'movie', 'security_7days', 
                    'security_delivery', 'in_special_panic', 'in_special_gift','score');
                break;
            case 'score':
                $fields = array('id', 'title', 'description',
                    'use_score', 'quantity',
                    'price_start','view',
                    'movie', 'start_time', 'end_time', 'security_7days', 'security_delivery',
                    'cash_deposit','paipin_activity_id','is_delicacy','auction_count');
                break;
            case 'paipin':
                $fields = array('id', 'uid', 'shop_id', 'category_id', 'title', 'description', 'price',
                'maxprice', 'quantity',
                'price_start','view',
                'movie', 'start_time', 'end_time', 'security_7days', 'security_delivery',
                'cash_deposit','paipin_activity_id','is_delicacy','auction_count');
                break;
            case 'xianzhi':
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity', 'movie', 'security_7days', 'security_delivery');
                break;
            default:
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity', 'movie', 'security_7days', 'security_delivery');
                break;
        }
        if($info['type']=='paipin'){
            $M_auaction_per=M('auaction_permission');
            if($M_auaction_per->where(array('uid'=>API_UID,'product_id'=>$id))->find()){
                $result['is_auaction_permission']=1;
            }else{
                $result['is_auaction_permission']=0;
            }
        }
        $result['identify_price'] = get_table_field($info['category_id'],'product_category_id','price','identify') | 0;
        $info3=$M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
        foreach ($fields as $field){
            $result[$field] = $info3[$field];
        }
        $result['im_account']=get_username($info['uid']);
        $M_product_image = M('product_image');
        $images = $M_product_image->where(array('product_id'=>$id))->select();
        foreach ($images as $image) {
            $result['images'][] = array(
                'id' => $image['id'],
                'path' => get_cover($image['cover_id'], 'path')
            );
        }
        
        $result['movie'] = array(
            'thumb_image_path'=>get_url(get_movie($result['movie'],'thumb_cover_id')),
            'id' => $info['movie'],
            'path' => mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Uploads/Movie/' . get_movie($result['movie'], 'savepath') . get_movie($result['movie'], 'savename'),
            'mime' => get_movie($result['movie'], 'mime')
        );       
        
        //组合属性
        $M_option=M('product_option');
        $o_names=$M_option->where(array('product_id'=>$id,'pid'=>0))->select()|0;         
        foreach ($o_names as &$item){
            $item['_child']=$M_option->where(array('pid'=>$item['id']))->select();
        }
        if($info['shop_id']){
            $result['shop_title']=get_table_field($info['shop_id'],'id','title','shop');
        }
        //组合价格
        $M_product_option_price=M('product_option_price');
        $result['option_price']=$M_product_option_price
        ->where(array('product_id'=>$id))->field('product_option_id,price')->select()|$result['price'];

        if($result['uid']!=0 && isset($result['score']) && $result['score']>0){
            $result['allow_quantity'] = floor(M('member')->where('uid='.$result['uid'])->getField('score')/$result['score']);
        }else{
            $result['allow_quantity'] = -1;
        }

        $result['option']=$o_names;
        response(1, $result);
    }
    
    /**
     * @param int id
     * 获取商品属性价格
     */
    public function getOptionPrice(){
        params_exist(array('id'));
        $id=I('post.id');
        !get_table_field($id,'id','id','product') && response(-2,'','商品不存在');
        $result=M('product_option_price')
        ->where(array('product_id'=>$id))->field('product_option_id,price')->select();
        if($result){
            response(1,$result);
        }else{
            $price=get_table_field($id,'id','price','producdt');
            $price ? response(1,$price) : response(-1);
        }
    }
    /**
     * 新增商品
     * 
     * @param string token 登录标识
     * @param string type 商品类型
     * @author Ringo Chan<334258471@qq.com>
     */
    public function add(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('type'));
        
        $M_product = M('product');
        $M_shop = M('shop');
        $M_product_image = M('product_image');
        
        $type = I('post.type');
        $score = (int)I('post.score',0);
        !get_table_field($type, 'name', 'id', 'product_type') && response(-2, '', '非法分类');
        $data = array(); // 结果集
        switch ($type) {
            case 'putong':
                $shop_id = $M_shop->where(array('uid'=>API_UID, 'status'=>1))->getfield('id');
                !$shop_id && response(-2, '', '账户没有开通店铺或店铺已被停用');
                
                params_exist(array('title', 'category_id', 'price', 'quantity', 'description', 'address', 'security_7days', 'status'));

                $data = params_post(array('title', 'category_id', 'price', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'security_7days', 'status'));
                
                $data['uid'] = API_UID;
                $data['shop_id'] = $shop_id;
                empty($data['title']) && response(- 1, '', '商品名称不能为空');
                empty($data['address']) && response(- 1, '', '店铺地址不能为空');
                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入商品价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                // !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $data['address']) && response(-1, '', '店铺地址长度必须在2~50个字符');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('product', $data['status']) && response(-1, '', '请选择商品状态');

                break;
            case 'paipin':
                $shop_id = $M_shop->where(array('uid'=>API_UID, 'status'=>1))->getfield('id');
                !$shop_id && response(-2, '', '账户没有开通店铺或店铺已被停用');
                
                params_exist(array('title', 'category_id', 'price', 'maxprice', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'start_date', 'start_hour', 'end_date', 'end_hour', 'security_7days', 'security_delivery', 'status'));

                $data = params_post(array('title', 'category_id', 'price', 'maxprice', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'start_date', 'start_hour', 'end_date', 'end_hour', 'security_7days', 'security_delivery', 'status'));
                
                !checkDateIsValid($data['start_date']) && response(-1, '', '开始时间格式有误');
                !getStatus('hours', $data['start_hour']) && response(-1, '', '开始时间整点格式有误');
                !checkDateIsValid($data['end_date']) && response(-1, '', '结束时间格式有误');
                !getStatus('hours', $data['end_hour']) && response(-1, '', '结束时间整点格式有误');
                
                $data['uid'] = API_UID;
                $data['shop_id'] = $shop_id;
                $data['start_time'] = strtotime($data['start_date'] . " " . getStatus('hours', $data['start_hour']) . ":00");
                $data['end_time'] = strtotime($data['end_date'] . " " . getStatus('hours', $data['end_hour']) . ":00");

                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                empty($data['title']) && response(- 1, '', '商品名称不能为空');
                empty($data['address']) && response(- 1, '', '店铺地址不能为空');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入起拍价格，不能小于1');
                !(is_numeric($data['maxprice']) && $data['maxprice'] > 0) && response(-1, '', '请输入立即成交价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                !get_table_field($data['province_id'], 'province_id', 'province_id', 'hat_province') && response(-2, '', '请选择发货地的省份');
                !get_table_field($data['city_id'], 'city_id', 'city_id', 'hat_city') && response(-2, '', '请选择发货地的城市');
                !get_table_field($data['area_id'], 'area_id', 'area_id', 'hat_area') && response(-2, '', '请选择发货地的区县');
                // !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $data['address']) && response(-1, '', '详细地址长度必须在2~50个字符');
                $data['start_time'] <= NOW_TIME && response(-1, '', '开始时间不能低于当前时间');
                $data['start_time'] >= $data['end_time'] && response(-1, '', '结束时间不能低于开始时间');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('security_delivery', $data['security_delivery']) && response(-1, '', '承诺发货时间不能为空');
                !getStatus('product', $data['status']) && response(-1, '', '请选择商品状态');

                break;
            case 'dingzhi':
                $shop_id = $M_shop->where(array('uid'=>API_UID, 'status'=>1))->getfield('id');
                !$shop_id && response(-2, '', '账户没有开通店铺或店铺已被停用');
                
                params_exist(array('verify', 'title', 'category_id', 'description', 'price', 'end_time', 'over_day', 'over_persent', 'province_id', 'city_id', 'area_id', 'address', 'security_7days', 'security_delivery'));
                
                $data = params_post(array('verify', 'title', 'category_id', 'description', 'price', 'end_time', 'over_day', 'over_persent', 'province_id', 'city_id', 'area_id', 'address', 'security_7days', 'security_delivery'));
                
                !checkDateIsValid($data['end_time']) && response(-1, '', '交货期限时间格式有误');
                
                $info = $M_product->where(array('verify'=>$data['verify'], 'uid'=>array('neq', API_UID), 'type'=>'paizhao', 'status'=>1))->find();
                !$info && response(-2, '', '邀请码有误');
                
                $data['end_time'] = strtotime($data['end_time'] . " 00:00:00");
                $data['uid'] = API_UID;
                $data['to_uid'] = $info['uid'];
                $data['shop_id'] = $shop_id;

                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                empty($data['title']) && response(- 1, '', '商品名称不能为空');
                empty($data['address']) && response(- 1, '', '店铺地址不能为空');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入起拍价格，不能小于1');
                $data['end_time'] < NOW_TIME && response(-1, '', '交货期限不能低于当前时间');
                empty($data['end_time']) && response(-1, '', '请选择交货期限或不是时间戳');
                empty($data['over_day']) && !is_int($data['over_day'])  && response(-1, '', '每延迟周期不能为空或不是数字');
                empty($data['over_persent']) && !is_int($data['over_persent']) && response(-1, '', '补偿百分比不能为空或不是数字');
                !get_table_field($data['province_id'], 'province_id', 'province_id', 'hat_province') && response(-2, '', '请选择发货地的省份');
                !get_table_field($data['city_id'], 'city_id', 'city_id', 'hat_city') && response(-2, '', '请选择发货地的城市');
                !get_table_field($data['area_id'], 'area_id', 'area_id', 'hat_area') && response(-2, '', '请选择发货地的区县');
                // !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $data['address']) && response(-1, '', '详细地址长度必须在2~50个字符');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('security_delivery', $data['security_delivery']) && response(-1, '', '承诺发货时间不能为空');
                
                break;
            case 'xianzhi':
                params_exist(array('title', 'category_id', 'price', 'quantity', 'description', 'security_7days', 'status'));
                
                $data = params_post(array('title', 'category_id', 'price', 'quantity', 'description', 'security_7days', 'status'));
                
                $data['uid'] = API_UID;

                !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入商品价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('product', $data['status']) && response(-1, '', '请选择商品状态');
                
                break;
            case 'paizhao':
                params_exist(array('title', 'category_id', 'price_start', 'price_end', 'description', 'security_7days', 'security_delivery'));
                
                $data = params_post(array('title', 'category_id', 'price_start', 'price_end', 'description', 'security_7days', 'security_delivery'));
                
                $data['uid'] = API_UID;
                $data['status'] = 1;
                $data['verify'] = getRandCode(3, 'string') . time() . getRandCode(3, 'string');

                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !is_numeric($data['price_start']) && $data['price_start'] < 0 && response(-1, '', '请输入商品价格，不能小于1');
                !is_numeric($data['price_end']) && $data['price_end'] < 0 && response(-1, '', '请输入商品价格，不能小于1');
                $data['price_start'] > $data['price_end'] && response(-1, '', '价格区间：最低价格不能高于最高价格');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('security_delivery', $data['security_delivery']) && response(-1, '', '承诺发货时间不能为空');
                
                break;
            default:
                break;
        }
        
        $data['type'] = $type;
        $data['create_time'] = NOW_TIME;
        $data['update_time'] = NOW_TIME;

        $data['score'] = $score;
        $id = $M_product->add($data);
        	
        $id <= 0 && response(-9, '', '添加失败，未知错误！');
        
        /* 定制商品成功后改变对应拍照购状态 */
        if ($type == 'dingzhi') {
            $M_product->where(array('verify'=>$data['verify'], 'uid'=>array('neq', API_UID), 'type'=>'paizhao', 'status'=>1))->setField('status', 0);
        }
        	
        /* 商品图片 */
        $pics = I('post.pics');
        
        foreach ($pics as $pic) {
            $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
        }
        
        /* 商品视频 */
        $movie = I('post.movie');
        $M_product->where(array('id'=>$id))->save(array('movie'=>$movie));
        
        $movie_thumb=I('movie_thumb_id');        
        if($movie_thumb){
            M('movie')->where(array('id'=>$movie))->save(array('thumb_cover_id'=>$movie_thumb));
        }
        
        $result['id'] = $id;
        $type == 'paizhao' && $result['verify'] = $data['verify'];
        
        response(1, $result);
    }
    
    /**
     * 编辑商品
     * 
     * @param string token 登录凭证
     * @param integer id 商品编号
     * @author Ringo Chan<334258471@qq.com>
     */
    public function edit(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        params_exist(array('id'));
    
        $M_product = M('product');
        $M_shop = M('shop');
        $M_product_image = M('product_image');
        
        $id = I('post.id');
        $product_info = $M_product->where(array('id'=>$id, 'uid'=>API_UID))->find();
        !$product_info && response(-2, '', '非法参数编号');
        $product_info['status'] == 1 && response(-2, '', '请先把商品下架再编辑');
        
        $type = $product_info['type'];
        !get_table_field($type, 'name', 'id', 'product_type') && response(-2, '', '非法分类');
    
        $data = array(); // 结果集

        $score = (int)I('post.score',0);
        switch ($type) {
            case 'putong':
                $shop_id = $M_shop->where(array('uid'=>API_UID, 'status'=>1));
                !$shop_id && response(-2, '', '账户没有开通店铺或店铺已被停用');
    
                params_exist(array('title', 'category_id', 'price', 'quantity', 'description', 'address', 'security_7days','in_special_panic'));
    
                $data = params_post(array('title', 'category_id', 'price', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'security_7days','in_special_panic'));
                empty($data['title']) && response(- 1, '', '商品名称不能为空');
                // empty($data['address']) && response(- 1, '', '店铺地址不能为空');
                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入商品价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('security_delivery', $data['security_delivery']) && response(-1, '', '承诺发货时间不能为空');
    
                break;
            case 'paipin':
                $shop_id = $M_shop->where(array('uid'=>API_UID, 'status'=>1));
                !$shop_id && response(-2, '', '账户没有开通店铺或店铺已被停用');
    
                params_exist(array('title', 'category_id', 'price', 'maxprice', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'start_date', 'start_hour', 'end_date', 'end_hour', 'security_7days', 'security_delivery'));
    
                $data = params_post(array('title', 'category_id', 'price', 'maxprice', 'quantity', 'description', 'province_id', 'city_id', 'area_id', 'address', 'start_date', 'start_hour', 'end_date', 'end_hour', 'security_7days', 'security_delivery'));
    
                !checkDateIsValid($data['start_date']) && response(-1, '', '开始时间格式有误');
                !getStatus('hours', $data['start_hour']) && response(-1, '', '开始时间整点格式有误');
                !checkDateIsValid($data['end_date']) && response(-1, '', '结束时间格式有误');
                !getStatus('hours', $data['end_hour']) && response(-1, '', '结束时间整点格式有误');
    
                $data['start_time'] = strtotime($data['start_date'] . " " . getStatus('hours', $data['start_hour']) . ":00");
                $data['end_time'] = strtotime($data['end_date'] . " " . getStatus('hours', $data['end_hour']) . ":00");
    
                !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入起拍价格，不能小于1');
                !(is_numeric($data['maxprice']) && $data['maxprice'] > 0) && response(-1, '', '请输入立即成交价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                !get_table_field($data['province_id'], 'province_id', 'province_id', 'hat_province') && response(-2, '', '请选择发货地的省份');
                !get_table_field($data['city_id'], 'city_id', 'city_id', 'hat_city') && response(-2, '', '请选择发货地的城市');
                !get_table_field($data['area_id'], 'area_id', 'area_id', 'hat_area') && response(-2, '', '请选择发货地的区县');
                //!preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $data['address']) && response(-1, '', '详细地址长度必须在2~50个字符');
                // !preg_match('/^.{1,50}+$/u', $data['address']) && response(-1, '', '详细地址长度必须在2~50个字符');
                $data['start_time'] <= NOW_TIME && response(-1, '', '开始时间不能低于当前时间');
                $data['start_time'] >= $data['end_time'] && response(-1, '', '结束时间不能低于开始时间');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
                !getStatus('security_delivery', $data['security_delivery']) && response(-1, '', '承诺发货时间不能为空');
    
                break;
            case 'xianzhi':
                params_exist(array('title', 'category_id', 'price', 'quantity', 'description', 'security_7days'));
    
                $data = params_post(array('title', 'category_id', 'price', 'quantity', 'description', 'security_7days'));
    
                // !preg_match('/[\x{4e00}-\x{9fa5}A-Za-z0-9-_.\/\s]{1,60}+$/u', $data['title']) && response(-1, '', '商品名称长度必须在2-60个字符之间');
                !get_table_field($data['category_id'], 'id', 'id', 'product_category') && response(-2, '', '商品分类为空或没有找到匹配的分类！');
                !(is_numeric($data['price']) && $data['price'] > 0) && response(-1, '', '请输入商品价格，不能小于1');
                !(preg_match('/[\d]+$/', $data['quantity']) && intval($data['quantity']) >= 0) && response(-1, '', '请输入商品库存，不能小于0');
                !getStatus('security_7days', $data['security_7days']) && response(-1, '', '支持7天无理由退货不能为空');
    
                break;
            default:
                break;
        }
        $data['score'] = $score;
        $data['type'] = $type;
        $data['movie'] = I('post.movie');
        $data['update_time'] = NOW_TIME;
        
        $pics = I('post.pics');
        
        $old=$M_product_image->where(array('product_id'=>$id))->field('cover_id')->select();
        $old_image=array();
        foreach ($old as $olditem){
            $old_image[]=$olditem['cover_id'];
        }
        foreach ($old_image as $olditem){
            if(!in_array($olditem, $pics)){
                $M_product_image->where(array('product_id'=>$id, 'cover_id'=>$olditem))
                ->delete();
            }
        }
        foreach ($pics as $pic) {
            if(in_array($pic, $old_image)){                 
            }else{
                $M_product_image->add(array('product_id'=>$id, 'cover_id'=>$pic));
            }
        }
        
        $movie=I('post.movie');
        $movie_thumb=I('movie_thumb_id');
        if($movie_thumb){
            M('movie')->where(array('id'=>$movie))->save(array('thumb_cover_id'=>$movie_thumb));
        }
        $M_product->where(array('id'=>$id, 'uid'=>API_UID))->save($data) !== false ? response(1) : response(-9);
    }
    
    /**
     * 获取商品专题抢购会信息
     *
     * @param string token 登录凭证
     * @param integer product_id 商品编号
     * @author Ringo Chan<334258471@qq.com>
     */
    public function getProductPanic(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        params_exist(array('product_id'));
        
        $M_product = M('product');
        $M_product_special_panic = M('product_special_panic');
        
        $product_id = I('post.product_id');
        $product_info = $M_product->where(array('id'=>$product_id, 'uid'=>API_UID))->find();
        !$product_info && response(-2, '', '非法参数编号');
        
        $product_panic_info = $M_product_special_panic->where(array('product_id'=>$product_id))->field(array('special_panic_id', 'condition_price', 'discount'))->find();
        
        response(1, $product_panic_info);
    }
    
    /**
     * 获取商品专题选礼物信息
     * 
     * @param string token 登录凭证
     * @param integer product_id 商品编号
     * @author Ringo Chan<334258471@qq.com>
     */
    public function getProductGift(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('product_id'));
        
        $M_product = M('product');
        $M_product_special_gift = M('product_special_gift');
        
        $product_id = I('post.product_id');
        $product_info = $M_product->where(array('id'=>$product_id, 'uid'=>API_UID))->find();
        !$product_info && response(-2, '', '非法参数编号');
        
        $product_gift_info = $M_product_special_gift->where(array('product_id'=>$product_id))->field(array('special_gift_id'))->select();
        
        response(1, $product_gift_info);
    }
    
    /**
     * 加入商品专题抢购会
     * 
     * @param string token 登录凭证
     * @param integer product_id 商品编号
     * @param integer special_panic_id 抢购时间编号
     * @param integer condition_price 满足价格条件
     * @param integer discount 折扣编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addProductPanic(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('product_id', 'special_panic_id', 'condition_price', 'discount'));
        $data = params_post(array('product_id', 'special_panic_id', 'condition_price', 'discount'));
        
        $M_product = M('product');
        $M_product_special_panic = M('product_special_panic');
        $M_special_panic = M('special_panic');
        
        $product_info = $M_product->where(array('id'=>$data['product_id'], 'uid'=>API_UID))->find();
        !$product_info && response(-2, '', '非法参数编号');
        
        $special_panic_info = $M_special_panic->where(array('id'=>$data['special_panic_id'], 'status'=>1))->find();
        !$special_panic_info && response(-2, '', '非法参数时间编号');
        
        $M_product->where(array('id'=>$data['product_id'], 'uid'=>API_UID))->save(array('in_special_panic'=>1,'update_time'=>NOW_TIME));
        getStatus('discount', $data['discount']) == null &&  response(-2, '', '非法参数折扣编号');
        
        $data['create_time'] = NOW_TIME;
        
        $M_product_special_panic->where(array('product_id'=>$data['product_id']))->delete();
        $M_product_special_panic->add($data) !== false ? response(1) : response(-9);
    }
    
    /**
     * 加入商品专题选礼物
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addProductGift(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('product_id', 'special_gift_id'));
        $data = params_post(array('product_id', 'special_gift_id'));
        
        $M_product = M('product');
        $M_product_special_gift = M('product_special_gift');
        $M_special_gift = M('special_gift');
        
        $product_info = $M_product->where(array('id'=>$data['product_id'], 'uid'=>API_UID))->find();
        !$product_info && response(-2, '', '非法参数编号');
        $M_product->where(array('id'=>$data['product_id'], 'uid'=>API_UID))->save(array('in_special_gift'=>1,'update_time'=>NOW_TIME));
        if (is_array($data['special_gift_id'])) {
            $data['special_gift_id'] = array_filter($data['special_gift_id']);
            $data['special_gift_id'] = array_unique($data['special_gift_id']);
        }
        
        foreach ($data['special_gift_id'] as $special_gift) {
            $info = $M_special_gift->where(array('id'=>$special_gift, 'status'=>1))->find();
            !$info && response(-2, '', '选礼物分类编号：' . $special_gift . ' 没有匹配对象');
        }
        
        $M_product_special_gift->where(array('product_id'=>$data['product_id']))->delete();
        foreach ($data['special_gift_id'] as $special_gift) {
            $M_product_special_gift->add(array('product_id' => $data['product_id'], 'special_gift_id' => $special_gift, 'create_time' => NOW_TIME));
        }
        
        response(1);
    }
    
    /**
     * 获取商品分类列表
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getCategoryTree(){
        $gid = I('post.gid');
        $M_product_category = M('product_category');
        $filters['status'] = array('eq', 1);
        empty($gid) || $filters['gid'] = $gid;
        $list = $M_product_category->where($filters)->field('id, pid, gid, title, sort')->order('sort ASC, id ASC')->select();
        $list = list_to_tree($list);
        $list !== false ? response(1, $list) : response(-9);
    }
    
    /**
     * 获取当日整点抢购时间表
     * 
     * @param string type 搜索条件
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getPanicTimes(){
        $list = array();
        
        params_exist(array('type'));
        
        $type = I('post.type');
        
        $M_special_panic = M('special_panic');
        
        switch ($type) {
            case 'all':
                $M_special_panic_t=$M_special_panic->where(array('status'=>1));
                $list = $M_special_panic_t->order('id DESC')->select();
                break;
            case 'currday':

                $deadline_start = date('Y-m-d 00:00:00', time());
                $deadline_end = strtotime(date('Y-m-d 23:59:59', time()));

                $where['status']=array('eq',1);

                $M_special_panic_t=$M_special_panic->where($where);
                
                $list = $M_special_panic_t->order('id DESC')->select();
                break;
            case 'after':
                $M_special_panic_t=$M_special_panic->where(array('status'=>1, 'end_time'=>array('egt', NOW_TIME)));
                $list = $M_special_panic_t->select();
                break;
            default:
                response(-1, '', '非法参数');
                break;
        }
        $list !== false ? response(1, $list) : response(-9);
    }
    
    /**
     * 获取选礼物分类列表
     * 
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getGiftCategory(){
        static $list = array();
        
        if (empty($list)) {
            $list = S('CACHE_FRONT_GIFT_CATEGORY');
        }
        
        if (empty($list)) {
            $M_special_gift = M('special_gift');
            $list = $M_special_gift->where(array('status'=>1))->field(array('id', 'title', 'cover_id', 'sort'))->order('sort ASC, id ASC')->select();
            
            foreach ($list as $key => $item) {
                $list[$key]['image'] = get_cover($item['cover_id'], 'path');
                unset($list[$key]['cover_id']);
            }
            
            S('CACHE_FRONT_GIFT_CATEGORY', $list);
        }
        
        $list !== false ? response(1, $list) : response(-9);
    }
    
    /**
     * 竞拍报名
     * @param int product_id
     */
    public function paipinSignup(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
         
        params_exist(array('product_id'));
        $product_id=I('post.product_id');
         
        $M_product=M('Product');
        $M_member=M('member');
       
        $product_info=$M_product->field('cash_deposit,end_time,title,type')->find($product_id);
        empty($product_info) && response(-2,'','商品不存在');
        
        $product_info['type'] != 'paipin' && response(-1,'','当前商品不是竞拍商品');
        $member_info=$M_member->where(array('uid'=>API_UID))->find();        
        
        (int)$product_info['end_time'] < (int)NOW_TIME && response(-1,'','本次竞拍已结束');
        (double)$product_info['cash_deposit'] > (double)$member_info['amount'] && response(-1,'','余额不足');
        
        $M_auaction_per=M('auaction_permission');
        $M_auaction_per->where(array('uid'=>API_UID,'product_id'=>$product_id))->find() &&
        response(1,'','您已经已经提交保证金');
        
        $data=array();
        $data['product_id']=$product_id;
        $data['uid']=API_UID;
        $data['cash_deposit']=$product_info['cash_deposit'];
        $data['create_time']=NOW_TIME;
         
        $result=$M_auaction_per->add($data) ;
        empty($result)  && response(-9);
        $bill_data=array();
        $bill_data['uid']=API_UID;
        $bill_data['create_time']=NOW_TIME;
        $bill_data['title']='竟拍报名保证金 冻结金额'.$data['cash_deposit'];
        $bill_data['desc']=$product_info['title'];
        $bill_data['sign']='-';
        $bill_data['type']=3;
        $bill_data['money']=$data['cash_deposit'];
        $bill_data['status']=1;
        
        M('bill')->add($bill_data);
         
        $result= $M_member->where(array('uid'=>API_UID))->setDec('amount',$data['cash_deposit']);
        empty($result) && response(-9);
        $result=$M_member->where(array('uid'=>API_UID))->setInc('freeze_amount',$data['cash_deposit']);
        empty($result) && response(-9);
    
        response(1);
    }
    
    /**
     * 出价
     * @param int product_id
     * @param int money
     */
    public function bid(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        params_exist(array('product_id','money'));
        $product_id=I('post.product_id');
        $money=I('post.money');
      
        $M_bill= M('bill');
        $M_product=M('Product');
        $M_member=M('member');
        $M_auaction_per=M('auaction_permission');
        $M_auction_log=M('auction_log');
        
        !is_numeric($money) || empty($money) && response(-1,'','出价错误');
        
        $product_info=$product_info=$M_product
        ->field('cash_deposit,end_time,title,price_start')->find($product_id);
        empty($product_info) && response(-2,'','竞拍商品不存在');
        
        (int)$product_info['end_time'] < (int)NOW_TIME && response(-1,'','本次竞拍已结束');
        
        (int)$product_info['price_start'] > $money && response(-1,'','出价不能低于起拍价');
        
        $auaction_authority=$M_auaction_per->where(array('uid'=>API_UID,'product_id'=>$product_id));
        empty($auaction_authority) && response(-2,'','未报名');
        
        //最新出价
        $au_log_after=$M_auction_log->where(array('product_id'=>$product_id))
        ->order('id DESC')->find();
        
        //上一次出价
        $old_auction=$M_auction_log->where(array('product_id'=>$product_id,'uid'=>API_UID))->order('id DESC')->find();
        //判断是否重复竞拍
        if($au_log_after['id']){
            $au_log_after['id'] == $old_auction['id'] && response(-2,'','请等待别人出价');
        }
        //最高出价
        (int)$au_log_after['price'] >= (int)$money  && response(-1,'','出价不能低于当前最高出价');
        
        $member_map=array('uid'=>API_UID);       
        $member_info=$M_member->where($member_map)->find();
        (double)$money > (double)$member_info['amount'] && response(-1,'','账户余额不足');
        if($old_auction){  
            $refz_amount=$M_member->where($member_map)->setInc('amount',$old_auction['price']);
            $refz_amount<=0 && response(-1,'','解冻资金出错');
            $reefed=$M_member->where($member_map)->setDec('freeze_amount',$old_auction['price']);            
            if($reefed<=0){
                $M_member->where($member_map)->setDec('amount',$old_auction['price']);
                response(-1,'','解冻资金出错');
            }
            
            if($refz_amount  && $reefed )
            {            
                $bill_data=array();
                $bill_data['uid']=API_UID;
                $bill_data['create_time']=NOW_TIME;
                $bill_data['sign']='+';
                $bill_data['money']=$money;
                $bill_data['type']=4;        
                $bill_data['title']='竟拍解冻 金额：'.$money;
                $bill_data['desc']=$product_info['title'].' 竟拍解冻 金额：'.$money;
                $bill_data['status']=1;            
                $a=$M_bill->add($bill_data);
                $a<0 && response(-1,'','资金计算出错');
            }
            else{
                response(-1,'','系统异常');
            }
        }
        
        $re_fz=$M_member->where($member_map)->setInc('freeze_amount',$money);
        $re_fz <=0 && response(-2,'','冻结资金1出错');
        $re_fz_dm=$M_member->where($member_map)->setDec('amount',$money);
        if($re_fz_dm <=0){
            $M_member->where($member_map)->setDec('freeze_amount',$money);
            response(-2,'','更新用户余额出错');
        }
        if($re_fz && $re_fz_dm){
            $data=array();
            $data['uid']=API_UID;
            $data['product_id']=$product_id;
            $data['create_time']=NOW_TIME;
            $data['price']=$money;
            $data['auction_no']=(int)$au_log_after['auction_no'] +1;
            
            $result=$M_auction_log->add($data);
            $result<0 && response(-1,'','系统出现错误');            
            
            //账单信息
            $bill_data=array();
            $bill_data['uid']=API_UID;
            $bill_data['create_time']=NOW_TIME;
            $bill_data['title']='竟拍出价'.$money;
            $bill_data['desc']=$product_info['title'].' 竞拍冻结资金  金额：'.$money;
            $bill_data['sign']='-';
            $bill_data['money']=$money;
            $bill_data['type']=3;
            $bill_data['status']=1;
            
            $a=$M_bill->add($bill_data);
            $a<=0 && response(-1,'加入账单错误');
            
            $a=$M_product->where(array('id'=>$product_id))->setInc('auction_count',1);
            $a<=0 && response(-1,'数据更新出错');
        }
        response(1);
    }
    
    /**
     * 竞拍出价记录
     * @param int product_id
     * @param int page
     * @param int pagesize
     */
    public function bidLog(){

        params_exist(array('product_id'));
        $product_id=I('post.product_id');
        $page=I('post.page',1);
        (int)$page <=0 & $page=1;
        
        $pagesize=I('post.pagesize',10);
        $offset=($page-1)*$pagesize;
        
        $M_auction_log=M('auction_log');
        $map=array('product_id'=>$product_id);
        $total=$M_auction_log->where($map)->count();
        $list=$M_auction_log->where($map)->field('create_time time,uid,price')->limit($offset,$pagesize)->order('id DESC')->select();
        foreach($list as &$item){
            $item['format_time']=time_format($item['time'],'Y-m-d H:m:s');
            $nickname=get_nickname($item['uid']);            
            $item['nickname']=substr_replace($nickname,'****',-4);
        }
        $result=array();
        $result['total']=$total;
        $result['result']=$list;
        
        $list ? response(1,$result) : response(-2);
    }
    
    /**
     * 保证金需知
     */
    public function bidClause(){
        response(1,C('BID_CASH_DEPOSIT_CLAUSE'));
    }
    
    /**
     * 商品属性
     */
    public function productOption(){
        params_exist(array('product_id'));
        
        $id=I('post.product_id');
        $M_product_option=M('product_option');
        $M_product_option_price=M('product_option_price');
        $map=array('product_id'=>$id);
        
        $options = $M_product_option->where(array(
            'product_id' => $id,
            'pid' => 0
        ))
        ->field('id,title')
        ->select();

        
        if ($options) {
            foreach ($options as &$_item) {
                $_item['_child'] = $M_product_option->where(array(
                    'pid' => $_item['id']
                ))
                ->field('id,title')->select();
            }
        }
        $options_price=$M_product_option_price->where($map)
        ->field('id,price,product_option_id')->select();
        
        $result['option']=$options;
        $result['option_price']=$options_price;
        
       $options ? response(1,$result) : response(-2);
    }
    
    /**
     * 新增/编辑 商品选项
     *
     * @param integer id 商品选项编号
     * @param integer pid 商品选项父级编号
     * @param string text 商品选项属性值
     * @author Ringo Chan <334258471@qq.com>
     */
    public function editOption($id = 0, $pid = 0, $product_id = 0, $text = ''){
        $M_product = M('product');
        $M_product_option = M('product_option');
    
        if (empty($id) && empty($pid)) {
            empty($product_id) && !$M_product->find($product_id) && response(-1, null, '非法参数');
            empty($text) && response(-1, null, '选项标题不能为空');
    
            $id = $M_product_option->add(array('product_id'=>$product_id, 'pid'=>0, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } elseif (empty($id)) {
            empty($text) && response(-1, null, '属性标题不能为空');
            empty($pid) && response(-1, null, '非法参数');
    
            $info = $M_product_option->find($pid);
            !$info && response(-2, null, '非法参数');
    
            $id = $M_product_option->add(array('product_id'=>$info['product_id'], 'pid'=>$pid, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } else {
            empty($text) && response(-1, null, '属性标题不能为空');
            !$M_product_option->find($id) && response(-1, null, '非法参数');
    
            $M_product_option->where(array('id'=>$id))->save(array('title'=>$text, 'update_time'=>NOW_TIME));
        }
    
        response(1, array('id'=>$id));
    }
    
    /**
     * 删除 商品选项
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOption($id = 0){
        $M_product_option = M('product_option');
    
        !$M_product_option->find($id) && response(-1, null, '非法参数');
    
        $M_product_option->where(array('id|pid'=>$id))->delete();
    
        response(1);
    }
    
    /**
     * 增加 商品选项价钱
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addOptionPrice($product_id = 0, $ids = 0, $price = 0){
        $M_product = M('product');
        $M_product_option = M('product_option');
        $M_product_option_price = M('product_option_price');
    
        empty($product_id) && !$M_product->find($product_id) && response(-1, null, '非法参数');
        empty($ids) && response(-1, null, '请选择选项');
        !is_numeric($price) && $price <= 0 && response(-1, null, '价格不能低于1元');
    
        !is_array($ids) && $ids = str2arr($ids);
        $option_category_count = $M_product_option->where(array('product_id' => $product_id, 'pid'=>0))->count() | 0;
        count($ids) != $option_category_count && response(-1, null, '缺少组合选项');
    
        sort($ids, SORT_NUMERIC);
        $ids = arr2str($ids);
        $info = $M_product_option_price->where(array('product_id'=>$product_id, 'product_option_id'=>$ids))->find();
        $info && response(-2, null, '组合选项已存在');
        $id = $M_product_option_price->add(array('product_id'=>$product_id, 'product_option_id'=>$ids, 'price'=>$price, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        $id > 0 ? response(1, array('id'=>$id)) : response(-9);
    }
    
    /**
     * 修改 商品选项价钱
     */
    public function editOptionPrice($id = 0, $price = 0) {
        $M_product_option_price = M('product_option_price');
    
        !$M_product_option_price->find($id) && response(-1, null, '非法参数');
        !is_numeric($price) && $price <= 0 && response(-1, null, '价格不能低于1元');
    
        $boolean = $M_product_option_price->where(array('id'=>$id))->setField(array('price'=>$price, 'update_time'=>NOW_TIME));
        $boolean !== false ? response(1, array('id'=>$id)) : response(-9);
    }
    
    /**
     * 删除 商品选项价钱
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOptionPrice($id = 0){
        $M_product_option_price = M('product_option_price');
        !$M_product_option_price->find($id) && response(-1, null, '非法参数');
        $M_product_option_price->where(array('id'=>$id))->delete();
        response(1);
    }
    
    public function getHots() {
        $productList = M('product')->where(array('is_top'=>array('eq', 1)))->field(array('id', 'type', 'title', 'view', 'price'))->limit(0,5)->select();
        foreach ($productList as &$product) {
            $product['image'] = M('product_image')->where(array('product_id'=>$product['id']))->order('id ASC')->find();
            $product['image'] = get_url($product['image']['cover_id']);
        }
        response(1, $productList);
    }
    
    public function getGroups() {
        $group = I('post.group', 0);
        $filters['group'] = $group;
        $groupList = M('product_group')->where($filters)->order('sort ASC, id DESC')->select();
        foreach ($groupList as &$group) {
            $group['image'] = get_url($group['cover_id']);
        }
        response(1, $groupList);
    }
}
